// src/composables/chat/useMessage.ts
import { ref, watch, computed } from 'vue';
import { useSocket } from './useSocket';
import { useChatStore } from '@/stores/chat.store';

// Define message structure (adjust as needed)
interface ChatMessage {
  id: string;
  roomId: string;
  senderId: string;
  content: string;
  timestamp: number;
  // Add other relevant fields like sender name, avatar, message type, etc.
}

export function useMessage(roomId: string) {
  const chatStore = useChatStore();
  const { socket, isConnected, emit, on, off } = useSocket();

  // Use computed property to get messages for the current room from the store
  const messages = computed(() => chatStore.getMessagesByRoom(roomId));

  const setupMessageListener = () => {
    // Listen for incoming messages for this specific room or globally
    // Adjust the event name based on your backend implementation
    const messageEventHandler = (message: ChatMessage) => {
      console.log('Received message:', message);
      // Ensure the message belongs to the current room before adding
      if (message.roomId === roomId) {
        chatStore.addMessage(message);
        // TODO: Add logic for notifications, scrolling, etc.
      }
    };

    on('chat_message', messageEventHandler);

    // Clean up listener when the room changes or component unmounts
    // This should ideally be handled in the component using this composable
    // For example, using onUnmounted in the component:
    // onUnmounted(() => off('chat_message'));
  };

  const sendMessage = (content: string) => {
    if (!isConnected.value) {
      console.error('Cannot send message: Socket not connected.');
      // TODO: Notify user or queue message
      return;
    }
    if (!content.trim()) {
      console.warn('Cannot send empty message.');
      return;
    }

    // TODO: Get senderId from auth store or context
    const senderId = 'temp-user-id'; // Replace with actual user ID

    const message: Partial<ChatMessage> = {
      roomId,
      senderId,
      content,
      timestamp: Date.now(),
    };

    // Emit the message to the server
    // Adjust the event name based on your backend implementation
    emit('send_message', message, (ack: any) => {
      // Optional: Handle acknowledgment from server (e.g., message received)
      if (ack?.success) {
        console.log('Message sent and acknowledged:', message);
        // Optionally add the message to the store immediately
        // Or wait for the server to broadcast it back via 'chat_message'
        // chatStore.addMessage({ ...message, id: ack.messageId } as ChatMessage);
      } else {
        console.error('Message sending failed or not acknowledged:', ack);
        // TODO: Handle failed message sending (e.g., show error, retry)
      }
    });
  };

  // Fetch initial messages for the room (optional)
  const fetchMessages = async () => {
    // TODO: Implement API call or socket event to fetch historical messages
    console.log(`Fetching messages for room ${roomId}...`);
    // Example: emit('get_messages', { roomId }, (history) => chatStore.setMessages(roomId, history));
    // For now, we assume messages are loaded elsewhere or start empty
    if (!chatStore.rooms[roomId]) {
       chatStore.initRoom(roomId);
    }
  };

  // Setup listener when composable is initialized and socket is ready
  watch(isConnected, (newVal) => {
    if (newVal && roomId) {
      console.log(`Socket connected, setting up listeners for room ${roomId}`);
      // Potentially join a room on the server
      emit('join_room', { roomId });
      setupMessageListener();
      fetchMessages(); // Fetch messages once connected
    } else {
      // Handle disconnection or room change - cleanup might be needed
      off('chat_message'); // Clean up listener if socket disconnects
    }
  }, { immediate: true }); // Run immediately to handle existing connection

  // Initial fetch if already connected
  if (isConnected.value && roomId) {
    fetchMessages();
    setupMessageListener();
     emit('join_room', { roomId });
  }

  return {
    messages, // Computed ref to room messages
    sendMessage,
    // receiveMessage is handled internally by the listener
    fetchMessages, // Expose if manual fetching is needed
  };
}